package com.jplus.plugin.rpc.process;

import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.jplus.plugin.rpc.codec.NIODecoder;
import com.jplus.plugin.rpc.nio.NIO.NIORole;

public abstract class NIOProcess {

	protected final ConcurrentLinkedQueue<ByteBuffer> queue = new ConcurrentLinkedQueue<>();
	protected NIORole role;
	protected NIODecoder decoder;

	public NIOProcess(NIORole role, NIODecoder decoder) {
		this.role = role;
		this.decoder = decoder;
	}

	// 写
	public ByteBuffer parseWrite() {
		if (queue.isEmpty())
			return null;
		return queue.poll();
	}

	// 读
	public void parseRead(ByteBuffer buffer) {
		addMsg(execute(buffer));
	}

	// 添加写
	public void addMsg(ByteBuffer buffer) {
		if (buffer != null) {
			buffer.flip();
			queue.add(buffer);
		}
	}

	/**
	 * 执行
	 * 
	 * @param 读入的数据
	 * @return 写出的数据
	 */
	protected abstract ByteBuffer execute(ByteBuffer buffer);
}
